/**
 * 记录各个用户的偏好设置
 */
import { IDBPDatabase, openDB, deleteDB } from 'idb'
import Authorization from '@utils/authorization'

// 新增表记得修改版本号
function _openDB () {
  openDB('preference', 2, {
    upgrade (db, ov, nv) {
      const names = new Set(['DeviceData', 'DeviceShare'])
      const _names = db.objectStoreNames
      for (let i = 0; i < _names.length; i++) {
        names.delete(_names[i])
      }
      names.forEach((name) => {
        db.createObjectStore(name)
      })
    }
  }).then((db) => {
    db.close()
  })
}
_openDB()

class Preference {
  db: IDBPDatabase
  storeName: string
  constructor (storeName: string) {
    this.storeName = storeName
    openDB('preference').then((db) => {
      this.db = db
    })
  }

  getItem (key: string) {
    if (!this.db) return Promise.resolve(undefined)
    return this.db.get(this.storeName, Authorization.user.id + '_' + key)
  }

  setItem (key: string, value: any) {
    return this.db.put(this.storeName, value, Authorization.user.id + '_' + key)
  }
}

export const PreferenceDB = {
  DeviceData: new Preference('DeviceData'),
  DeviceShare: new Preference('DeviceShare')
}
